package gp.app;

import genetic.GPApplication;

import java.util.Observable;
import java.util.Observer;

import javax.swing.JFrame;

import org.jfree.chart.ChartFactory;
import org.jfree.chart.ChartPanel;
import org.jfree.chart.JFreeChart;
import org.jfree.chart.plot.PlotOrientation;
import org.jfree.data.xy.XYDataset;
import org.jfree.data.xy.XYSeries;
import org.jfree.data.xy.XYSeriesCollection;

@SuppressWarnings("serial")
public class XYSeriesView extends JFrame implements Observer {
	
    XYSeriesCollection visualizationData = new XYSeriesCollection();

    public void addTargetSeries(XYSeries tgt) {
    	visualizationData.addSeries(tgt);
    }
    
	public XYSeriesView(GPApplication app) {
		super("GPGraphView");
		
		app.addObserver(this);
		
		this.setSize(512, 300);
		this.setLocation(0, 200);
		this.setResizable(false);

        JFreeChart chart = createChart(visualizationData);
        ChartPanel chartPanel = new ChartPanel(chart);
//        chartPanel.setPreferredSize(new java.awt.Dimension(500, 270));
        setContentPane(chartPanel);
        
        visualizationData.addSeries(app.getTargetXYSeries());
	}

    private static JFreeChart createChart(XYDataset dataset) {
        JFreeChart chart = ChartFactory.createXYLineChart(
            "",
            "", 
            "", 
            dataset,
            PlotOrientation.VERTICAL,
            false,
            false,
            false
        );
        return chart;
    }

	@Override
	public void update(Observable arg0, Object arg1) {
		visualizationData.addSeries(((GPApplication)arg0).calcBest());
		
    	if (visualizationData.getSeriesCount() >= 4)
    		visualizationData.removeSeries(1);
	}
}
